package com.rcn.dal.hibernate;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.rcn.core.Patient;
import com.rcn.dal.interfaces.IPatientDAO;
import com.rcn.hibernate.HibernateUtil;

/**
 * Logs important info and errors but NEVER print an id.
 * Prints the stacktrace when an exception is catched.(TODO check this, should we print the stacktrace?)
 * @author Nicolas
 */
public class PatientDAO extends BaseDAO implements IPatientDAO{
	private static Logger log = LogManager.getLogger(PatientDAO.class.getName());
	
	@Override
	public Patient getByIdNumber(int idNumber) {
		Session session = HibernateUtil.getSession();
		
		String hql = "FROM Patient p WHERE p.idNumber = :idNumber";
		Query query = session.createQuery(hql);
		query.setParameter("idNumber",idNumber);
		Patient patient = null;
		try{
			patient = (Patient) query.uniqueResult();

		}catch(HibernateException e){
			log.error("An error ocurred trying to get patient with idNumber "+idNumber,e);
			throw e;
		}catch (ClassCastException e){
			log.error("Parse error trying to get patient with idNumber: "+idNumber
					+". This error should never happen, but just in case.",e);
			throw e;
		}
		return patient;
	}
	
	public int deleteById(long id){
    	Session session = HibernateUtil.getSession();
		
		String hql = "DELETE FROM Patient p WHERE p.id = :id";
		Query query = session.createQuery(hql);
		query.setParameter("id",id);
		int rows = 0;
		try{
			rows =  query.executeUpdate();
		}catch(HibernateException e){
			log.error("An error ocurred trying to delete patient.",e);
			throw e;
		}
		return rows;
    }
}
